package com.xone.xapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONUtils {
	
	public static JSONObject getJSONObjectFromString(String str) {
		JSONObject o = null;
		try {
			o = new JSONObject(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;
	}
	
	public static JSONObject getJSONObjectForKey(JSONObject object, String key) {
		JSONObject o = null;
		try {
			o = object.getJSONObject(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;
	}
	
	public static JSONArray getJSONArrayForKey(JSONObject object, String key) {
		JSONArray o = null;
		try {
			o = object.getJSONArray(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;
	}
	
	public static String getStringFromJSONObject(JSONObject object, String key) {
		try {
			return object.getString(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getStringFromJSONArray(JSONArray object, int index) {
		try {
			return object.getString(index);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static JSONObject getJSONObjectFromJSONArray(JSONArray object, int index) {
		try {
			return object.getJSONObject(index);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Boolean getBooleanFromJSONObject(JSONObject object, String key) {
		try {
			return object.getBoolean(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean isNullOrEmptyList(List list) {
		return null == list || list.isEmpty();
	}
	
	public static List<JSONObject> getJSONListFromIdentifyString(String result, String identify) {
		try {
			List<JSONObject> listJson = new ArrayList<JSONObject>();
			JSONObject jsonObject = new JSONObject(result);
			JSONArray list = jsonObject.getJSONArray(identify);
			if (null != list) {
				for (int i = 0; i < list.length(); i++) {
					listJson.add(list.getJSONObject(i));
				}
			}
			return listJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}

}
